package net.luoran.dvm.core;

import lombok.extern.java.Log;
import net.luoran.dvm.common.annotation.AuthToken;
import net.luoran.dvm.common.annotation.LoginToken;
import net.luoran.dvm.common.annotation.PassToken;
import net.luoran.dvm.common.util.AuthUtil;
import net.luoran.dvm.common.util.JwtUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Log
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Class clazz = handlerMethod.getMethod().getDeclaringClass();
        //检查是否有PassToken注释，有则跳过认证
        if (clazz.isAnnotationPresent(PassToken.class) || method.isAnnotationPresent(PassToken.class)) {
            return true;
        }
        //检查有没有需要用户权限LoginToken的注解
        LoginToken loginToken = null;
        if (method.isAnnotationPresent(LoginToken.class)) {
            loginToken = method.getAnnotation(LoginToken.class);
        }
        if (clazz.isAnnotationPresent(LoginToken.class)) {
            loginToken = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(LoginToken.class);
        }

        AuthToken authToken = null;
        if (method.isAnnotationPresent(AuthToken.class)) {
            authToken = method.getAnnotation(AuthToken.class);
        }
        if (clazz.isAnnotationPresent(AuthToken.class)) {
            authToken = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(AuthToken.class);
        }

        if (loginToken != null && loginToken.required()) {
            // 执行认证
            String tokenHeader = request.getHeader(JwtUtil.TOKEN_HEADER);// 从 http 请求头中取出 token
            if (tokenHeader == null) {
                log.info("没有token");
                response.sendRedirect("login");
                return false;
            }
            String token = tokenHeader.replace(JwtUtil.TOKEN_PREFIX, "");
            if (token == null) {
                log.info("没有token");
                response.sendRedirect("login");
                return false;
            }
            boolean b = JwtUtil.verify(token);
            if (b == false) {
                log.info("token不存在或已失效，请重新获取token");
                response.sendRedirect("login");
                return false;
            }
            return true;
        }
        if (authToken != null && authToken.required()) {
            String authStr = request.getHeader(AuthUtil.TOKEN_KEY);
            if (authStr == null) {
                log.info("没有AuthToken");
                throw new RuntimeException("非法访问！[403]");
            }
            if (!AuthUtil.verify(authStr)) {
                log.info("授权已过期或授权码已经失效！");
                throw new RuntimeException("授权已过期或授权码已经失效！[403]");
            }
            return true;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
